<template>
  <div class="history-card-wrapper" title="" ref="wrapper">
    <div class="title">
      <h3>历史记录</h3>
      <search-bar
        ref="searchBar"
        class="search-bar"
        v-model:searchValue="searchValue"
        :width="125"
        :height="28"
        :class="{
          close: !searching,
        }"
      ></search-bar>
      <ul class="utils">
        <li class="iconfont icon-search" @click="search()" title="搜索">S</li>
        <li class="iconfont icon-financial_omit type-select" title="筛选">
          X
          <ul class="history-type-list">
            <li
              :class="{ bgLight: historyType === 0 }"
              @click="historyType = 0"
            >
              文章
            </li>
            <li
              :class="{ bgLight: historyType === 1 }"
              @click="historyType = 1"
            >
              资源
            </li>
          </ul>
        </li>
        <li
          v-if="!searching"
          class="iconfont icon-clear"
          title="清空所有记录"
          @click="cleanAllHistory"
        >
          C
        </li>
        <li v-else class="iconfont icon-cancel" @click="searching = false">
          E
        </li>
      </ul>
    </div>
    <ul class="pages">
      <li class="pageDate">今天</li>
      <li
        v-for="(item, idx) of todayHistory"
        :key="idx"
        @click="toDetail(item)"
      >
        <h3>{{ item.title }}</h3>
        <h4>{{ formatDate(item.browseDate) }}</h4>
      </li>
      <li class="pageDate">之前</li>
      <li
        v-for="(item, idx) of beforeHistory"
        :key="idx"
        @click="toDetail(item)"
      >
        <h3>{{ item.title }}</h3>
        <h4>{{ formatDate(item.browseDate) }}</h4>
      </li>
      <li ref="loading" class="loading"></li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import SearchBar from '../utils/SearchBar.vue'
import { ref, watch, computed, ComputedRef, Ref } from 'vue'
import { UserStateLogin, useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { confirm } from '@/utils/popup'
import { format } from '@/utils/time'

let searching = ref(false)
let searchValue = ref('')
let historyType = ref(0)

watch(historyType, () => {
  // fetchHistory()
})

let todayHistory = computed(() => {
  return filteredHistory?.value?.filter(({ browseDate }) => {
    let od = new Date(browseDate)
    od.setHours(0, 0, 0, 0)
    let td = new Date()
    td.setHours(0, 0, 0, 0)
    return od.getDate() === td.getDate()
  })
})

let beforeHistory = computed(() => {
  return filteredHistory.value?.filter(({ browseDate }) => {
    let od = new Date(browseDate)
    od.setHours(0, 0, 0, 0)
    let td = new Date()
    td.setHours(0, 0, 0, 0)
    return od.getDate() !== td.getDate()
  })
})

const userStore = useUserStore()
let userState = userStore.$state as UserStateLogin

let history: ComputedRef<App.Content[]> = computed(() => {
  let history = historyType.value
    ? userState.history?.content?.sources.map((_) => _)
    : userState.history?.content?.articles.map((_) => _)
  if (historyType.value) {
    history.forEach((item) => {
      item.routePath = `/source/${item.id}`
    })
  } else {
    history?.forEach((item) => {
      item.routePath = `/article/${item.id}`
    })
  }
  return history
})

let filteredHistory = computed(() => {
  return history?.value?.filter((item) => {
    return (
      item.title.includes(searchValue.value) ||
      item.digest.includes(searchValue.value)
    )
  })
})

// TODO: FetchHistory
// function fetchHistory() {
//       if (historyType.value) {
//         this.$store.commit('fetchHistorySourceAbstracts')
//       } else {
//         this.$store.commit('fetchHistoryArticleAbstracts')
//       }
//     }

let searchBar: Ref<HTMLInputElement | null> = ref(null)
function search() {
  searching.value = true
  let dom = searchBar.value as HTMLInputElement
  dom.focus()
}

const router = useRouter()
function toDetail(item: App.Content) {
  router.push({
    path: item.routePath,
  })
}

function cleanAllHistory() {
  confirm('清空历史记录？').then((flag) => {
    if (flag) {
      if (historyType.value) {
        userStore.cleanHistorySource()
      } else {
        userStore.cleanHistoryArticle()
      }
    }
  })
}

function formatDate(date: number) {
  return format(date, 'MM-dd HH:mm')
}

// TODO: Scrollload
// onMounted(() => {
//
//     this.$scrollLoad({
//       root: this.$refs.wrapper,
//       loadingComponent: this.$refs.loading,
//       callback: () => {
//         this.fetchHistory()
//       },
//     })
// })
</script>

<style scoped lang="scss">
@import 'style/shortcut';
@import 'style/config';

.history-card-wrapper {
  width: 300px;
  padding-bottom: 5px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 0 10px 1px $light;

  &:hover {
    cursor: default;
  }

  .title {
    $h: 40px;
    position: relative;
    display: flex;
    justify-content: space-between;
    padding: 0 13px;
    font-size: 15px;
    height: $h;
    line-height: $h;
    font-weight: bold;
    color: $black;
    border-bottom: 1px solid $light;

    .search-bar {
      position: absolute;
      left: 40%;
      top: 50%;
      transform: translateY(-50%);
      background-color: white;
      z-index: 1;

      &.close {
        opacity: 0 !important;
        width: 0 !important;
      }
    }

    .utils {
      @include flex();

      > li {
        $a: $h * 0.8;
        position: relative;
        margin-right: 5px;
        font-weight: normal;
        width: $a;
        height: $a;
        line-height: $a;
        font-size: 18px;
        border-radius: 3px;
        transition: 0.3s;

        &:hover {
          background-color: $light;
          cursor: pointer;
        }
      }

      .type-select {
        &:hover ul {
          transform: translate(-50%, 0);
          opacity: 1;
        }

        ul {
          position: absolute;
          top: 100%;
          left: 50%;
          transform: translate(-50%, -10px);
          opacity: 0;

          transition: 0.2s;

          width: 70px;

          background-color: white;
          box-shadow: 0 0 3px 0.2px $gray;
          border-radius: 3px;

          overflow: hidden;

          > li {
            height: 30px;
            line-height: 30px;
            font-size: 13px;

            &:hover {
              background-color: $light;
              cursor: pointer;
            }
          }
        }
      }
    }
  }

  .pages {
    padding: 3px 0;
    max-height: 300px;
    overflow-y: auto;

    li {
      box-sizing: border-box;

      $h: 30px;
      margin: 3px 10px;

      @include flex();

      border-radius: 5px;

      color: $black;
      font-size: 14px;
      line-height: $h;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      &:hover,
      h3:hover,
      h4:hover {
        cursor: pointer;
      }

      h3 {
        width: 70%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      &:not(.pageDate):hover {
        background-color: $light;
      }

      &.pageDate {
        padding: 0 10px;
        font-weight: bold;

        &:hover {
          cursor: auto;
        }
      }

      &:not(.pageDate) {
        padding-left: 20px;
      }
    }
  }
}
</style>
